package com.headline.utils;

import io.jsonwebtoken.*;
import org.junit.jupiter.api.Test;

import java.util.Date;
import java.util.UUID;

public class JwtTest2 {

    // 一天的时间/ms
    private long ONE_DAY = 1000*60*60*24;

    // 密钥
    private String signature = "admin";

    @Test
    public void CreateTokenTest() {
        JwtBuilder jwtBuilder = Jwts.builder();
        String jwtToken = jwtBuilder
                // 1、header
                // 设置类型为JWT令牌
                .setHeaderParam("typ", "JWT")
                // 设置算法为HMAC SHA-256
                .setHeaderParam("alg", "HS256")
                // 2、payload
                // 添加自定义声明
                .claim("username", "tom")
                .claim("role", "admin")
                // 声明主题
                .setSubject("admin-test")
                // 设置JWT过期时间
                .setExpiration(new Date(System.currentTimeMillis() + ONE_DAY))
                // 设置JWT的唯一标识符，这里生成了一个随机的UUID作为JWT的ID
                .setId(UUID.randomUUID().toString())
                // 3、signature
                // 设置用于签名的算法和密钥，算法为HS256，传入指定密钥
                .signWith(SignatureAlgorithm.HS256, signature)
                // 拼接
                .compact();
        System.out.println(jwtToken);
    }


    @Test
    public void JwtParse() {
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InRvbSIsInJvbGUiOiJhZG1pbiIsInN1YiI6ImFkbWluLXRlc3QiLCJleHAiOjE3MzM0MTA0NTYsImp0aSI6ImZkNmE3NzRlLWU2MDAtNDQ3My05MzM2LWJmM2NlNDVhZjVhNiJ9.-h8yaV17Q27vMSbgmVyKyl-hAbhvXH9xMrLOOs7n9Mo";
        JwtParser jwtParser = Jwts.parser();
        Jws<Claims> claimsJwts = jwtParser.setSigningKey(signature).parseClaimsJws(token);
        Claims body = claimsJwts.getBody();
        System.out.println(body);
    }

}
